package com.edu.robot.modules.im.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.edu.robot.model.enums.ResultCodeEnum;
import com.edu.robot.model.error.BizException;
import com.edu.robot.modules.im.controller.vo.MessageVO;
import com.edu.robot.common.service.ChannelManger;
import com.edu.robot.modules.im.service.IMService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.CompletableFuture;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-30 16:28
 **/


@RestController
@RequestMapping("/sse")
@Slf4j
public class SSEController {

	@Autowired
	private ChannelManger channelManger;

	@Autowired
	private IMService imService;

	/**建立SSE连接*/
	@RequestMapping(value = "/event", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
	public SseEmitter createSse(String sessionId, String content,String tenantId,Boolean openSearch,Boolean fistMessage) {

		log.info("SSEController createSse sessionId:{},content:{},tenantId:{},openSearch:{}",sessionId,content,tenantId,openSearch);

		MessageVO messageVO = new MessageVO();

		if(StringUtils.isAllBlank(sessionId,content,tenantId)){
			throw new BizException(ResultCodeEnum.PARAM_INVALID,"参数不能为空");
		}
		String userId = StpUtil.getLoginIdAsString();

		SseEmitter sse = channelManger.createSse(userId);

		//异步处理消息
		CompletableFuture.runAsync(()->{

			try {
				log.info("开始异步处理消息"); // 添加日志
				messageVO.setSessionId(sessionId);
				messageVO.setContent(content);
				messageVO.setTenantId(tenantId);
				messageVO.setOpenSearch(openSearch);
				messageVO.setUserId(userId);
				messageVO.setFirstMessage(fistMessage);
				imService.sendMessage(messageVO);
			}catch (Exception e){
				log.error("异步处理消息失败",e);
			}

		});


		return sse;

	}


}
